import React, { Component } from 'react'
import { Space, Select, Button, Typography } from 'antd';
import store from "../redux/store"
import { addAction, subtractAction, addAsyncAction } from '../redux/count_action'
const { Option } = Select;
const { Title } = Typography;


export default class Count extends Component {
    state = {
        // 下拉框绑定值
        selectVal: 1
    }

    // 改变下拉触发
    handleChange = (value) => {
        this.setState({
            selectVal: +value
        })
    }
    // 加
    add = () => {
        const { selectVal } = this.state
        // 调用 store.dispatch 方法派发一个事件
        store.dispatch(addAction(selectVal))
    }
    // 减
    subtract = () => {
        const { selectVal } = this.state
        // 调用 store.dispatch 方法派发一个事件
        store.dispatch(subtractAction(selectVal))
    }
    // 奇数加
    addIfOdd = () => {
        const { selectVal } = this.state
        if (store.getState() % 2 !== 0) {
            store.dispatch(addAction(selectVal))
        }
    }

    addIfAsync = () => {
        const { selectVal } = this.state
        // 调用异步的action更新状态
        store.dispatch(addAsyncAction(selectVal, 500))
    }

    componentDidMount() {
        // 当redux中的状态发生变化时会自动触发这个回调函数
        store.subscribe(() => {
            // 传递一个空对象更新渲染函数
            this.setState({})
        })
    }


    render() {
        return (
            <div>
                <div>
                    {/* store.getState() 从redux中获取数据 */}
                    <Title level={4}>当前数据和：{store.getState()}</Title>
                </div>

                <div>
                    <Space size='small'>
                        <Select defaultValue={this.state.selectVal} style={{ width: 150 }} onChange={this.handleChange}>
                            <Option value="1">1</Option>
                            <Option value="2">2</Option>
                            <Option value="3">3</Option>
                        </Select>
                        <Button type="primary" onClick={this.add}>加</Button>
                        <Button type="primary" onClick={this.subtract}>减</Button>
                        <Button type="primary" onClick={this.addIfOdd}>奇数加</Button>
                        <Button type="primary" onClick={this.addIfAsync}>异步增加</Button>
                    </Space>
                </div>
            </div>
        )
    }
}
